import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_give/repository/api.dart';
import 'package:flutter_give/utils/LogUtils.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:rapid_kit/rapid_kit.dart';

import '../../common_ui/dialog/dialog_title.dart';
import '../../common_ui/loading.dart';
import '../../repository/datas/TangeEqData.dart';
import '../../repository/datas/onlineInfo.dart';
import '../../route/route_utils.dart';
import '../../route/routes.dart';
import '../../tgpage/device/share.dart';
import '../../tgpage/event/notification.dart';
import '../../tgpage/media/cloud_replay.dart';
import '../../tgpage/media/live.dart';
import '../../tgpage/media/local_replay.dart';
import '../../theme.dart';
import '../../utils/constants.dart';
import '../../utils/sp_utils.dart';
import '../hot_key/hot_key_page.dart';
import '../subpackage/eqsetting_page.dart';
import '../subpackage/share_page.dart';
import '../tab_page.dart';
import 'home_vm.dart';
import '../../common_ui/dialog/dialog_factory.dart';

/// 首页
class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<StatefulWidget> createState() {
    return HomePageState();
  }
}

class HomePageState extends State<HomePage> with WidgetsBindingObserver {
  static final GlobalKey<HomePageState> globalKeytwo =
      GlobalKey<HomePageState>();

  // 获取类
  HomeViewModel viewModel = HomeViewModel();

  // 上拉刷新-下拉加载组件
  RefreshController refreshController = RefreshController();

  // 指令示例
  late Pipe _pipe;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance?.addObserver(this);
    // GlobalData.store.dispatch(initHome());

    // refreshOrLoad(false);

    // 设置背景颜色
    // setSystemUIOverlayStyle();

    // 探鸽设备列表
    viewModel.tangeeqlist.clear();
    viewModel.getTANGEList();
  }

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance?.removeObserver(this);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) async {
    // TODO: implement didChangeAppLifecycleState
    super.didChangeAppLifecycleState(state);
    switch (state) {
    //进入应用时候不会触发该状态 应用程序处于可见状态，并且可以响应用户的输入事件。它相当于 Android 中Activity的onResume
      case AppLifecycleState.resumed:
        String data = await SpUtils.getString(Constants.SP_ZHSL_TABINDEX);
        print("进入前台${data}");
        if (data == '1') {
          LogUtils.w("执行第二页");
          HotKeyPageState.globalKey.currentState?.reloadData();
        } else {
          WidgetsBinding.instance.addPostFrameCallback((_) {
            setSystemUIOverlayStyle();
            reloadData();
          });
        }
        break;
    //应用状态处于闲置状态，并且没有用户的输入事件，
    // 注意：这个状态切换到 前后台 会触发，所以流程应该是先冻结窗口，然后停止UI
      case AppLifecycleState.inactive:
        print("应用处于闲置状态，这种状态的应用应该假设他们可能在任何时候暂停 切换到后台会触发======");
        break;
    //当前页面即将退出
      case AppLifecycleState.detached:
        print("当前页面即将退出======");
        break;
    // 应用程序处于不可见状态
      case AppLifecycleState.paused:
        print("应用处于不可见状态 后台======");
        break;
      case AppLifecycleState.hidden:
        // TODO: Handle this case.
    }
  }

  // 重新加载
  void reloadData() {
    // 在这里实现重新加载数据的逻辑
    print("==============加载第一页数据=============");

    viewModel.tangeeqlist.clear();
    viewModel.getTANGEList();

    // 确保页面渲染完成后再执行 setSystemUIOverlayStyle
    WidgetsBinding.instance.addPostFrameCallback((_) {
      setSystemUIOverlayStyle();
    });
  }

  void setSystemUIOverlayStyle() {
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Color(0xFFbdeddd),
      statusBarIconBrightness: Brightness.dark,
    ));
  }

  @override
  Widget build(BuildContext context) {
    setSystemUIOverlayStyle();
    return ChangeNotifierProvider(
      create: (context) => viewModel,
      child: Scaffold(
        appBar: AppBar(
          toolbarHeight: 60,
          title: Text(
            '我的设备',
            style: TextStyle(
              color: Color(0xFF454547),
              fontWeight: FontWeight.w600,
              fontSize: 20.sp,
              fontFamily: "PingFang SC",
            ),
          ),
          flexibleSpace: Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter, // 从顶部开始
                end: Alignment.bottomCenter, // 到底部结束
                colors: [Color(0xFFbdeddd), Color(0xFFdaece9)], // 渐变颜色
              ),
            ),
          ),
          elevation: 0,
          actions: [
            IconButton(
              icon: CircleAvatar(
                backgroundColor: Color(0xFF00c888), // 圆形底图的背景颜色
                radius: 18, // 圆形底图的半径
                child: Icon(
                  Icons.add,
                  color: Colors.white, // 加号图标的颜色
                  size: 24, // 加号图标的大小
                ),
              ),
              onPressed: () {
                // 在这里添加按钮点击事件的逻辑
                print("===============添加设备点击事件==============");
                RouteUtils.pushForNamed(context, RoutePath.EqaddTypePage,
                    arguments: {"name": "添加设备"});
              },
            ),
          ],
        ),
        body: SafeArea(
          child: Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/app_img/one.png'), // 替换为你的图片路径
                fit: BoxFit.cover, // 设置图片的填充方式
              ),
            ),
            child: Column(
              children: [
                Expanded(
                  child: Container(
                    color: Color(0xFFF1F1F1).withOpacity(0.8),
                    // 设置背景颜色为 #f1f1f1，并添加透明度
                    padding: EdgeInsets.only(top: 15),
                    // 设置上边距为 20
                    child: SmartRefresher(
                      controller: refreshController,
                      enablePullDown: true,
                      enablePullUp: true,

                      header: ClassicHeader(
                        //无特殊要求就可以用这个换下文案就行了
                        height: 45.0,
                        releaseText: '松开刷新',
                        refreshingText: '刷新中',
                        completeText: '刷新完成',
                        idleText: '下拉刷新',
                      ),
                      footer: ClassicFooter(
                        //无特殊要求就可以用这个换下文案就行了
                        loadStyle: LoadStyle.ShowWhenLoading,
                        completeDuration: Duration(microseconds: 50),
                        canLoadingText: '松开刷新',
                        noDataText: '没有更多数据啦',
                        loadingText: '刷新中',
                        idleText: '上拉加载',
                      ),
                      onLoading: () {
                        LogUtils.w("开始加载");
                        // 上拉加载的逻辑
                        // refreshOrLoad(true);
                        viewModel.initListData().then(
                              (value) => refreshController.loadComplete(),
                            );
                      },
                      onRefresh: () {
                        // 下拉刷新的逻辑
                        viewModel.tangeeqlist.clear();
                        viewModel.pageSize = 10;
                        viewModel.pageNum = 1;
                        viewModel.getTANGEList();
                        refreshController.refreshCompleted();
                      },
                      child: _buildHomeView(), // 列表参与刷新和加载
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 没有数据
  Widget _noDataView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset(
            'assets/app_img/nodataeq.png', // 替换为你的图片路径
            width: 200,
            height: 180,
          ),
          SizedBox(height: 20), // 图片和文字之间的间距
          Text(
            '无设备',
            style: TextStyle(fontSize: 16, color: Color(0xFF656467)),
          ),
          SizedBox(height: 20), // 文字和按钮之间的间距
          _buildLoginButton()
        ],
      ),
    );
  }

  // 添加设备按钮
  Widget _buildLoginButton() {
    return SizedBox(
      width: 250,
      child: ElevatedButton(
        onPressed: () {
          RouteUtils.pushForNamed(context, RoutePath.EqaddTypePage,
              arguments: {"name": "添加设备"});
        },
        style: ElevatedButton.styleFrom(
          backgroundColor: SampleThemeConfigure.colorPrimary,
          foregroundColor: SampleThemeConfigure.colorForeground,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(30),
          ),
          padding:
              const EdgeInsets.only(top: 8, bottom: 13, left: 50, right: 50),
          // 分别设置上下左右的内边距
          elevation: 0,
          shadowColor: Colors.transparent,
        ),
        child: const Text(
          '添加设备',
          style: TextStyle(fontSize: 17),
          // textAlign: TextAlign.center, // 确保文字居中
        ),
      ),
    );
  }

// 视频组件
  Widget _homestView() {
    return Consumer<HomeViewModel>(builder: (context, vm, child) {
      return Container(
        // color: Color(0xFFf1f1f1),
        child: ListView.builder(
          // 内部自己计算高度-不然SingleChildScrollView没有高度，渲染不出来
          shrinkWrap: true,
          // 关闭ListView滚动-使用SingleChildScrollView滚动
          // 不然会出现 滚动下面轮播图不懂
          // 滚动轮播图-才会全部滚动-因为使用的是SingleChildScrollView滚动
          physics: NeverScrollableScrollPhysics(),
          itemBuilder: (context, index) {
            return _ListItView(vm.tangeeqlist?[index], index);
          },
          itemCount: vm.tangeeqlist?.length ?? 0,
        ),
      );
    });
  }

  // 视频组件
  Widget _buildHomeView() {
    return Consumer<HomeViewModel>(builder: (context, vm, child) {
      if (vm.tangeeqlist == null || vm.tangeeqlist!.isEmpty) {
        return _noDataView();
      } else {
        return _homestView();
      }
    });
  }

  // 每一项
  Widget _ListItView(TangeEqData? item, int index) {
    return GestureDetector(
      child: Container(
        margin: EdgeInsets.only(
          top: 5,
          bottom: 10,
          left: 10,
          right: 10,
        ),
        padding: EdgeInsets.only(
          top: 10,
          bottom: 10,
          left: 10,
          right: 10,
        ),
        decoration: BoxDecoration(
          color: Color(0xFFFFFFFF),
          // border: Border.all(color: Colors.black12, width: 1),
          borderRadius: BorderRadius.all(Radius.circular(20)),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 第一行标题加粗
            Padding(
              padding: EdgeInsets.only(left: 10), // 向右偏移10
              child: Row(
                children: [
                  Text(
                    item?.deviceName ?? "",
                    style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 16,
                    ),
                  ),
                  SizedBox(width: 10), // 添加一些间距

                  if (item?.type == 2)
                    Container(
                      padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                      // 内边距
                      decoration: BoxDecoration(
                        color: Color(0xFFe1f1ff), // 背景颜色
                        borderRadius: BorderRadius.circular(20), // 圆角
                      ),
                      child: Text(
                        "共享",
                        style: TextStyle(
                          color: Color(0xFF2db6a6), // 文字颜色
                          fontSize: 12,
                        ),
                      ),
                    ),
                ],
              ),
            ),
            SizedBox(height: 0), // 添加间距

            // 第二行 设备id：1111
            Padding(
              padding: EdgeInsets.only(left: 10), // 向右偏移10
              child: InkWell(
                onTap: () {
                  print("点击");
                  if (item?.deviceId != null) {
                    Clipboard.setData(ClipboardData(text: "${item?.deviceId}"));
                    showToast("复制成功");
                  }
                },
                child: Row(
                  children: [
                    Text(
                      "设备ID: ${item?.deviceId ?? '未知'}",
                      style: TextStyle(fontSize: 14, color: Color(0xFF9c9c9c)),
                    ),
                    SizedBox(width: 8),
                    Icon(
                      Icons.content_copy,
                      size: 16,
                      color: Color(0xFF9c9c9c),
                    ),
                  ],
                ),
              ),
            ),

            SizedBox(height: 8), // 添加间距

            // 设备关闭
            if (item?.state == 0)
              Padding(
                padding: EdgeInsets.only(left: 0), // 向右偏移10
                child: Container(
                  height: 185,
                  width: double.infinity,
                  color: Colors.black, // 背景色为黑色
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center, // 上下居中
                    children: [
                      Text(
                        "设备已关闭",
                        style: TextStyle(fontSize: 14, color: Colors.white),
                      ),
                      SizedBox(height: 10), // 两行之间的间距
                      GestureDetector(
                        onTap: () async {
                          Loading.showLoading();
                          print("开启设备${item?.deviceId}"); // 点击时打印消息

                          // 创建实例
                          _pipe = Pipe.create(item?.deviceId ?? "");

                          // 连接设备
                          print("开启设备22");

                          // 2. 监听“连接状态”以作出响应
                          _pipe.listen((state) async {
                            LogUtils.w(state);
                            if (state == PipeState.established) {
                              try {
                                final resp =
                                    await InstructStandard.setDeviceSwitch(
                                        _pipe, 1);
                                if (!mounted) return;
                                if (resp.success) {
                                  bool eqswtich = await Api.instance
                                      .equploadrecord(
                                          ID: "${item?.id}", state: "1");
                                  if (eqswtich) {
                                    showToast("设置成功");
                                    setState(() {
                                      viewModel.tangeeqlist[index].state = 1;
                                      _pipe.abolish();
                                      _pipe.destroy();
                                      Loading.dismissAll();
                                    });
                                  }
                                }
                              } catch (e) {
                                // 捕获错误并关闭加载框
                                Loading.dismissAll();
                                print("设置设备开关时发生错误: $e");
                              }
                            }
                          });
                          _pipe.establish();

                          // final resp = await InstructStandard.setDeviceSwitch(
                          //     _pipe, 1);
                          // if (!mounted) return;
                          // if (resp.success) {
                          //   bool eqswtich = await Api.instance.equploadrecord(
                          //       ID: "${item?.id}", state: "1");
                          //   if (eqswtich) {
                          //     showToast("设置成功");
                          //     setState(() {
                          //       viewModel.tangeeqlist[index].state = 1;
                          //     });
                          //   }
                          // }
                        },
                        child: Container(
                          padding: EdgeInsets.symmetric(
                              horizontal: 15, vertical: 5), // 按钮的内边距
                          decoration: BoxDecoration(
                            color: Color(0xFF05ccb7), // 背景色
                            borderRadius: BorderRadius.circular(20), // 圆角
                          ),
                          child: Text(
                            "开启设备",
                            style: TextStyle(fontSize: 14, color: Colors.white),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),

            // 设备开启
            if (item?.state == 1)
              GestureDetector(
                onTap: () async {
                  OnlineInfo? data = await Api.instance
                      .eqonlineInfo(deviceid: "${item?.deviceId}");

                  LogUtils.w(data?.isOnline);
                  if (data?.isOnline == true) {
                    print("====================点击图片跳转页面==================");
                    final live = LivePage(
                      // 设备id
                      deviceId: item?.deviceId ?? "",
                      // 设备名称
                      deviceName: item?.deviceName ?? "",
                      // 设备播放类型
                      cameraCount: 1,
                      lan: false,
                    );

                    Navigator.push(
                      context,
                      MaterialPageRoute(builder: (context) => live),
                    );
                  }
                },
                onLongPress: () {
                  LogUtils.e("====================长按图片事件==================");
                  // 在这里添加长按图片事件的处理逻辑
                  DialogFactory.instance.showNeedeqListDialog(
                      context: context,
                      dismissClick: () {},
                      confirmClick: () async {
                        // 判断设备是否在线
                        final isOwner = item?.isOwner ?? false;
                        if (isOwner) {
                          // final resp =
                          //     await BindingService.unbind(item?.deviceId ?? "");
                          bool swticheq = await Api.instance
                              .equnbundle(deviceid: "${item?.id}" ?? "");
                          if (!context.mounted) return;
                          if (swticheq) {
                            showToast("删除成功");
                            setState(() {
                              viewModel.tangeeqlist?.clear();
                            });
                            viewModel.getTANGEList();
                          } else {
                            showToast("删除失败");
                          }
                        } else {
                          showToast("设备不在线，稍后重试");
                        }
                      });
                },
                child: Container(
                  height: 185,
                  width: double.infinity,
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: NetworkImage(
                        item?.coverImage ??
                            "http://jxj.zhgdyun.com:15551/image/6780d57201fdb41366cc19c9.png",
                      ),
                      fit: BoxFit.cover,
                    ),
                  ),
                  child: FadeInImage(
                    placeholder: NetworkImage(
                      "http://jxj.zhgdyun.com:15551/image/6780d57201fdb41366cc19c9.png",
                    ), // 加载时的占位图
                    image: NetworkImage(
                      item?.coverImage ??
                          "http://jxj.zhgdyun.com:15551/image/6780d57201fdb41366cc19c9.png",
                    ),
                    fit: BoxFit.cover,
                    imageErrorBuilder: (BuildContext context, Object exception,
                        StackTrace? stackTrace) {
                      // 当图片加载失败时，显示替换图片
                      return SizedBox(
                        width: double.infinity, // 设置宽度为无限大
                        height: 180, // 设置高度与 Container 一致
                        child: Image.network(
                          "http://jxj.zhgdyun.com:15551/image/6780d57201fdb41366cc19c9.png",
                          fit: BoxFit.cover,
                        ),
                      );
                    },
                  ),
                ),
              ),
            SizedBox(height: 8), // 添加间距

            // 第四行4个选项  每一个选项上下布局  上面是图片 下面是文字
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                if (item?.type == 2)
                  _buildOption(
                      imagePath: "assets/app_img/share.png",
                      text: "移除分享",
                      DEVICEID: "${item?.deviceId}",
                      ID: "${item?.id}"),
                if (item?.type == 1)
                  _buildOption(
                      imagePath: "assets/app_img/share.png",
                      text: "分享",
                      DEVICEID: "${item?.deviceId}",
                      ID: "${item?.id}"),
                _buildOption(
                    imagePath: "assets/app_img/playback.png",
                    text: "回放",
                    DEVICEID: "${item?.deviceId}",
                    NAME: "${item?.deviceName}"),
                _buildOption(
                    imagePath: "assets/app_img/title.png",
                    text: "名称",
                    DEVICEID: "${item?.deviceId}",
                    NAME: "${item?.deviceName}",
                    ID: "${item?.id}"),
                _buildOption(
                  imagePath: "assets/app_img/setting.png",
                  text: "设置",
                  DEVICEID: "${item?.deviceId}",
                  NAME: "${item?.deviceName}",
                  ID: "${item?.id}",
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  // 设置
  Widget _buildOption(
      {String? imagePath,
      String? text,
      String? DEVICEID,
      String? NAME,
      String? ID}) {
    return GestureDetector(
      onTap: () {
        // 在这里处理点击事件
        print("点击了$text");
        // 你可以根据 text 的值来执行不同的操作
        switch (text ?? "") {
          case "移除分享":
            // 处理分享
            DialogFactory.instance.showEqremoveshareDialog(
              context: context,
              dismissClick: () {
                //是否显示更新红点
              },
              confirmClick: () async {
                bool swtich = await Api.instance.gettrunshare(deviceid: ID);
                if (swtich) {
                  showToast("移除成功");
                  // viewModel.tangeeqlist.clear();
                  // Future.delayed(const Duration(milliseconds: 15000), () {
                  viewModel.tangeeqlist.clear();
                  viewModel.getTANGEList();
                  // });
                }
              },
            );
            break;
          case "分享":
            // 处理分享
            Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (context) => ShareminiPage(
                          deviceId: ID ?? "",
                          fromPage: "specificPage",
                        )));
            ShareminiPageState.globalKeyshare.currentState?.reloadData();

            break;
          case "回放":
            // 处理服务逻辑
            // Navigator.push(
            //     context,
            //     MaterialPageRoute(
            //         builder: (context) => CloudReplayPage(
            //               deviceId: DEVICEID ?? "",
            //               deviceName: NAME ?? "",
            //             )));
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => LocalReplayPage(
                  deviceId: DEVICEID ?? "",
                  deviceName: "2",
                ),
              ),
            );
            break;
          case "名称":
            SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
              statusBarColor: Color(0xFFffffff), // 设置状态栏颜色
              statusBarIconBrightness: Brightness.dark, // 设置状态栏图标亮度为暗色
            ));
            DialogInputFactory.instancess
                .showInputDialog(context, DEVICEID ?? "", NAME ?? "", ID ?? "",
                    onComplete: (success, message) {
              if (success) {
                print("操作成功: $message");
                setSystemUIOverlayStyle();
                viewModel.tangeeqlist.clear();
                viewModel.getTANGEList();
              } else {
                setSystemUIOverlayStyle();
                print("操作失败: $message");
              }
            });
            break;
          case "设置":
            // 处理设置逻辑
            // Navigator.push(context, MaterialPageRoute(builder: (context) => NotificationPage(deviceId: ID ?? "")));
            Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (context) => EqsettingPage(
                          deviceId: DEVICEID ?? "",
                          deviceName: NAME ?? "",
                          ID: ID ?? "",
                        )));
            break;
        }
      },
      child: Column(
        children: [
          Image.asset(
            imagePath ?? "",
            width: 24, // 设置图片宽度
            height: 24, // 设置图片高度
          ),
          SizedBox(height: 4), // 添加间距
          Text(text ?? ""),
        ],
      ),
    );
  }

// 判断摄像头类型
// int recognizedCameraCount(Primary primary) {
//   int cameraCount = 1;
//   if (primary.deviceAttributes?.contains("ipc-2ch") == true) {
//     cameraCount = 2;
//   } else if (primary.deviceAbilities?.contains("3-composed") == true) {
//     cameraCount = 3;
//   }
//   return cameraCount;
// }
}
